package com.example.demo.otherController;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author 谢辉
 * @Classname DownloadZip
 * @Description TODO
 * @Date 2021/1/6 10:36
 */
@Controller
public class DownloadZip {

    @RequestMapping("/downloadZip")
    public void downloadZip(HttpServletRequest req, HttpServletResponse resp, String name) throws Exception {
        try {
            // path是指欲下载的文件的路径。
            File file = new File("D:\\data20210106103755.zip");
            // 取得文件名。
            String filename = file.getName();
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            resp.reset();
            // 设置response的Header
            resp.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            resp.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(resp.getOutputStream());
            resp.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
